package com.example.capsule_chat0322.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.request.MessagesRequest;

/**
 * @Author zhuzhiming
 * @Date 2022/5/7 19:00
 */
public class ShowImageActivity extends AppCompatActivity {
    private ImageView show_image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_image);
        initView();//初始化UI控件
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initView() {

        show_image = findViewById(R.id.show_image);

        Intent intent = getIntent();
        String filePath = intent.getStringExtra("filePath");
        if (filePath != null) {
            LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
           String cacheKey = filePath.substring(filePath.lastIndexOf("/") + 1);
            final Bitmap[] bitmap = {(Bitmap) lruCache.get(cacheKey)};
            if (bitmap[0] != null) {
                show_image.setImageBitmap(bitmap[0]);
                return;
            }

            bitmap[0] = BitmapFactory.decodeFile(filePath);

            if(bitmap[0] != null){
                show_image.setImageBitmap(bitmap[0]);
                return;
            }

            MessagesRequest.getImage(Constant.IMAGE_SERVER_PATH + cacheKey, new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message message) {
                    bitmap[0] = (Bitmap)  lruCache.get(cacheKey);
                    show_image.setImageBitmap(bitmap[0]);
                    return true;
                }
            }));

        }


    }
}
